<template>
  <Dialog v-model="pickupDialogVisible" title="请输入自提门店信息" width="30%">
     <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
     <el-form-item prop="pickUpVerifyCode" label="选择自提门店">
        <el-select v-model="formData.pickUpStoreId" class="!w-280px" clearable>
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
     </el-form-item>
    

     </el-form>
     <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="pickupSubmit"> 确认核销 </el-button>
      <el-button @click="pickupDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as TradeOrderApi from '@/api/mall/trade/order'
import * as DeliveryPickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore'

/** 订单核销表单 */
defineOptions({ name: 'OrderPickUpStoreForm' })

const message = useMessage() // 消息弹窗

const pickupDialogVisible = ref(false)
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRules = reactive({
  pickUpStoreId: [{ required: true, message: '自提门店不能为空', trigger: 'blur' }]
})
const formData = ref({
  pickUpStoreId: null,
  pickUpVerifyCode: '', // 核销码
  orderId : 0,
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id:number,code:String) => {
  resetForm();
  formData.value.orderId = id;
  formData.value.pickUpVerifyCode = code;
  storeList.value = await DeliveryPickUpStoreApi.getListAllSimple()
  pickupDialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const storeList = ref<DeliveryPickUpStoreApi.DeliveryPickUpStoreVO[]>([]) // 门店列表

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const pickupSubmit = async () => {
  try {
    if(!formData.value.pickUpStoreId){
      message.error('请选择提货门店');
      return;
    }

    await message.confirm('确认核销订单吗？');

    // 提交请求
    formLoading.value = true
    let pickparam = {
      orderId: formData.value.orderId,
      pickUpVerifyCode: formData.value.pickUpVerifyCode,
      pickUpStoreId: formData.value.pickUpStoreId
    }
    await TradeOrderApi.pickUpTradeOrder(pickparam)
    message.success('核销成功')
    pickupDialogVisible.value = false
    // 发送操作成功的事件
    emit('success', true)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    pickUpStoreId: null,
  pickUpVerifyCode: '', // 核销码
  orderId : null,
  }
  formRef.value?.resetFields()
}

</script>
